/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.ytbolg.mcxa;
//import static net.ytbolg.mcxa.MCLaucherXA.l;

import net.ytbolg.mcxa.LangAndConfig.Lang;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
import net.ytbolg.mcxa.Launcher.GameInfo;
import static net.ytbolg.mcxa.Launcher.GameInfo.tpf;
//import javax.swingLauncher..JTextArea;
//import static net.ytbolg.mcxa.GameInfo.tpf;
//import sun.java2d.opengl.OGLRenderQueue;

/**
 *
 * @author Ytong
 */
public class Downloader extends javax.swing.JFrame {

    private final Thread thr;

    public void setUnzip(boolean x) {
        Download.s = x;
    }

    public void add(String LURL, String RURL) {
        Download.LURL.add(RURL);
        Download.RURL.add(LURL.replace(tpf, "/"));
    }

    public boolean start() {
        
        //  thr=    ;
        thr.start();
        //   new Downloader().setVisible(true);

        return true;
    }

    /**
     * Creates new form Downloader
     */
    public Downloader() {
      initComponents();
        System.out.println("执行构造方法");
        Download.LURL = new ArrayList();
        Download.RURL = new ArrayList();
        Download.j = jProgressBar1;
        Download.label = jLabel1;
        Download.list = jTextArea1;
        thr = new Thread(new Download());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("注：本窗口不会自动关闭");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jButton1.setText("取消");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("微软雅黑", 0, 13)); // NOI18N
        jTextArea1.setLineWrap(true);
        jScrollPane2.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1))
            .addComponent(jScrollPane2)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        thr.interrupt();
        dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
// TODO add your handling code here:
    }//GEN-LAST:event_formWindowActivated

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        setTitle(Lang.getLang("Lib_Title"));
        jButton1.setText(Lang.getLang("Lib_Button_Cancel"));//    // TODO add your handling code here:
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}

class Download implements Runnable {

    public static boolean s = true;
    public static ArrayList RURL;
    public static JProgressBar j;
    public static JLabel label;
    public static ArrayList LURL;
    public static JTextArea list;

    //@Override
    @Override
    public void run() {
        DefaultListModel m = new DefaultListModel();
        //  list = new JList(m);
        //    list.add
// System.out.println("开始下载" + "http://bmclapi.bangbang93.com/forge/getforge" + "/" + version + "/" + forgeversion);
        //  downloadFile("http://bmclapi.bangbang93.com/forge/getforge" + "/" + version + "/" + forgeversion, GameInfo.Rundir + tpf + "forgetmp.jar");
        //   downloadFile("http://bmclapi.bangbang93.com/versions/" + version + "/" + version + ".json", GameInfo.GameDir + tpf + "versions" + tpf + version + tpf + version + ".json");
        if (RURL.size() != LURL.size()) {
            //     m.add(m.getSize(),);
            list.setText(list.getText() + "\n" + Lang.getLang("Lib_CountNotEquals"));
            System.exit(1);
        }
        for (int i = 0; i < RURL.size(); i++) {
            //  m.add();
            System.out.println(list == null);
            list.setText(list.getText() + "\n" + "(" + (i + 1) + "/" + (RURL.size()) + ")" + Lang.getLang("Lib_Download") + LURL.get(i));
            downloadFile(RURL.get(i).toString(), LURL.get(i).toString());
        }
        //    JOptionPane.showMessageDialog(null, Lang.getLang("Lib_DownloadSucc"));

        j.setValue(0);
        label.setText("");

        if (s) {
            new Thread(new net.ytbolg.mcxa.unZipThread()).start();
        }

//new Thread(new unZipThread())).start();
        GameInfo.Downok = true;
     //   JOptionPane.showMessageDialog(null, "下载成功,下面将会运行forge安装程序，请在文件选择框里面输入游戏目录（已复制到剪切板）");
        // Clipboard clipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
        //  String vc = refContent.trim();  
        //  StringSelection ss = new StringSelection(vc);  

        // StringSelection selection = new StringSelection(GameInfo.GameDir);//复制step1:生成Transferable 接口对象。剪贴板只能放该类型的对象。 StringSelection类实现了Transferable接口。
        //   clipBoard.setContents(selection, null);//复制step2.第二个参数是Owner。
    }

    void downloadFile(String remoteFilePath, String localFilePath) {
        //System.out.println("远程文件地址" + remoteFilePath);
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        File xxxx = new File(f.getParent());
        xxxx.mkdirs();

//      f.mkdirs();
        try {
            net.ytbolg.mcxa.Output.Logger l = new net.ytbolg.mcxa.Output.Logger(0);
            l.Log("Downloading:" + remoteFilePath);
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            j.setMaximum(httpUrl.getContentLength());
            j.setValue(0);
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            int i = 0;
            while ((len = bis.read(b)) != -1) {
                i = i + len;
                j.setValue(i);
                label.setText(i / 1024 + "/" + (httpUrl.getContentLength() / 1024) + "KB");
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //  bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
